﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace IGolovkine.Core
{
    public struct Lock : IDisposable
    {
        private readonly object _obj;
        private Lock(object obj, TimeSpan timeout)
        {
            if (!Monitor.TryEnter(obj, timeout))
            {
                throw new TimeoutException("Failed to acquire lock");
            }
            _obj = obj;
        }

        public static IDisposable Enter(object obj, TimeSpan timeout)
        {
            return new Lock(obj, timeout);
        }

        public void Exit()
        {
            Monitor.Exit(_obj);
        }

        void IDisposable.Dispose()
        {
            this.Exit();
        }
    }
}
